<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="关键字" prop="keyName">
        <el-input
          v-model="queryParams.keyName"
          placeholder
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择仓库">
          <el-option
            v-for="store in stores"
            :key="store.id"
            :label="store.storeName"
            :value="store.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分类" prop="categoryId">
        <el-select
          v-model="queryParams.categoryId"
          placeholder="请选择..."
          size="mini"
          clearable
          ref="select"
          style="width: 300px"
        >
          <!-- // 设置一个隐藏的下拉选项，选项显示的是汉字label，值是value
          // 如果不设置一个下拉选项，下面的树形组件将无法正常使用-->
          <el-option hidden key="id" :value="queryParams.categoryId" :label="selectName"></el-option>
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
            ref="tree"
            node-key="id"
            :default-expand-all="true"
          >
            <span slot-scope="{ data }">
              <span>{{ data.label }}</span>
            </span>
          </el-tree>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['businessManagement:goods:add']"
        >添加物品</el-button>
      </el-col>
      
      <el-col :span="1.5" v-show="!(flag==1)">
        <el-button type="primary" plain icon="el-icon-house" size="mini" @click="handleStore">仓库管理</el-button>
      </el-col>
      <el-col :span="1.5" v-show="!(flag==1)">
        <el-button
          type="primary"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="handleCategory"
        >分类管理</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="index" align="center" label="序号" />

      <el-table-column label="物品" align="center" prop="goodsCover">
        <template slot-scope="scope">
          <image-preview :src="scope.row.goodsCover" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="goodsName" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="规格" align="center" prop="spec" />
      <el-table-column label="分类" align="center" prop="categoryId" :formatter="getcategoryById" />
      
      <el-table-column label="数量" align="center" prop="goodsStore.amounts" />
    
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['businessManagement:goods:edit']"
            v-if="!(flag==1)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['businessManagement:goods:remove']"
            v-if="!(flag==1)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            
            @click="handleGoods(scope.row)"
            v-hasPermi="['businessManagement:goods:remove']"
            v-if="flag"
          >选择扯物品</el-button>
          <!-- 出入库明细
          <el-popover
            placement="left"
            width="800"
            trigger="hover"
            :data="goodsList"
            @selection-change="handleSelectionChange"
          >
            <el-descriptions title="出入库明细" direction="vertical" :column="4" border>
              <el-descriptions-item label="序号" align="center">{{ scope.row.id }}</el-descriptions-item>
              <el-descriptions-item label="类型">{{ scope.row.customerName }}</el-descriptions-item>
              <el-descriptions-item label="操作时间" :span="2">{{scope.row.legalLeader}}</el-descriptions-item>
              <el-descriptions-item label="物品">{{ scope.row.openState }}</el-descriptions-item>
              <el-descriptions-item label="品牌">{{ scope.row.province}}</el-descriptions-item>
              <el-descriptions-item label="仓库">{{ scope.row.regCapital }}</el-descriptions-item>
              <el-descriptions-item label="数量">{{ scope.row.scope }}</el-descriptions-item>
              <el-descriptions-item label="单价">{{ scope.row.industry }}</el-descriptions-item>
            </el-descriptions>
            <el-button slot="reference" icon="el-icon-info" type="text" size="mini">出入库明细</el-button>
          </el-popover>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入物品名称" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择..."
            size="mini"
            clearable
            ref="select"
            style="width: 300px"
          >
            <!-- // 设置一个隐藏的下拉选项，选项显示的是汉字label，值是value
            // 如果不设置一个下拉选项，下面的树形组件将无法正常使用-->
            <el-option hidden key="id" :value="form.categoryId" :label="selectName"></el-option>
            <el-tree
              :data="categoryOptions"
              :props="defaultProps"
              @node-click="handleNodeClick"
              :expand-on-click-node="false"
              ref="tree"
              node-key="id"
              :default-expand-all="true"
            >
              <span slot-scope="{ data }">
                <span>{{ data.label }}</span>
              </span>
            </el-tree>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="图片" prop="goodsCover">
          <image-upload v-model="form.goodsCover" />
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input type="textarea" rows="5" v-model="form.spec" placeholder="请输入规格"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="goodsDesc">
          <el-input type="textarea" rows="5" v-model="form.goodsDesc" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">立即提交</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  categoryTreeselect,
  listCategorys
} from "@/api/businessManagement/category";
import {
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods
} from "@/api/businessManagement/goods";
import { listStores } from "@/api/businessManagement/store";

export default {
  name: "Goods",

  data() {
    return {
      // 判断是出库还是入库
      num: this.$route.query.num,
      // 获取是不是库存
      flag : this.$route.query.flag,
      // 所有的分类信息
      categorys: [],
      // 分类名称
      selectName: null,
      // 仓库信息数组
      stores: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyName: null,
        storeId: null,

        categoryId: null,

        goodsDesc: null
      },
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 物品分类信息下拉树结构数据
      categoryOptions: [],
      // 表单参数
      form: {
        id: null,
        goodsName: null,
        goodsCover: null,
        categoryId: null,
        brand: null,
        spec: null,
        goodsDesc: null
      },
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          {
            pattern: /^.{0,50}$/,
            message: "名称不能超50个字符",
            trigger: "blur"
          }
        ],
        categoryId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        goodsCover: [
          { required: true, message: "图片不能为空", trigger: "blur" }
        ],
        brand: [
          {
            pattern: /^.{0,50}$/,
            message: "品牌不能超50个字符",
            trigger: "blur"
          }
        ],
        spec: [
          {
            pattern: /^.{0,50}$/,
            message: "规格不能超50个字符",
            trigger: "blur"
          }
        ],
        goodsDesc: [
          {
            pattern: /^.{0,250}$/,
            message: "描述不能超250个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCategoryTreeselect();
  },
  methods: {
    handleGoods(row) {
      console.log(row);
      // 关闭当前浏览器页面
      // 跳转到入库页面
      this.$router.push("/businessManagement/opInfo/op?goodsId="+row.id+"&goodsName="+row.goodsName+"&num="+this.num)
    },
    // 根据分类id获取名字
    getcategoryById(row) {
      let categoryName = "";
      for (let category of this.categorys) {
        if (category.id == row.categoryId) {
          categoryName = category.categoryName;
        }
      }
      return categoryName;
    },
    // 结构树点击事件
    handleNodeClick(data) {
      this.queryParams.categoryId = data.id; // select绑定值为点击的选项的value
      this.form.categoryId = data.id; // select绑定值为点击的选项的value
      this.selectName = data.label; // input中显示值为label
      this.$refs.select.blur(); // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠
    },

    /** 查询分类树结构 */
    getCategoryTreeselect() {
      categoryTreeselect().then(response => {
        this.categoryOptions = response.data;
      });
    },

    // 分类弹出
    handleCategory() {
      let categoryPage = this.$router.resolve("/businessManagement/category");
      window.open(
        categoryPage.href,
        "_blank",
        "height=500, width=900,top=200,left=500"
      );
    },
    // 仓库弹出
    handleStore() {
      let storePage = this.$router.resolve("/businessManagement/store");
      window.open(
        storePage.href,
        "_blank",
        "height=500, width=900,top=200,left=500"
      );
    },
    /**
     * 出入库明细
     */
    handleStockBill(row) {},
    /** 查询物品信息列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      // 查询所有的仓库信息
      listStores().then(resp => {
        this.stores = resp.data;
      });
      // 获取所有的分类信息
      listCategorys().then(resp => {
        this.categorys = resp.data;
      });
    },
    // 取消按钮
    cancel() {
      this.selectName = null;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        goodsCover: null,
        categoryId: null,
        brand: null,
        spec: null,
        goodsDesc: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectName = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log(row);
      this.form = row;
      this.open = true;
      this.title = "修改物品信息";

      for (let category of this.categorys) {
        if (category.id == row.categoryId) {
          this.selectName = category.categoryName;
        }
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
            });
          }
          this.selectName = null;
          this.queryParams.categoryId = null;
          this.form.categoryId = null;
          this.getList();
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除物品信息编号为"' + row.id + '"的数据项？')
        .then(function() {
          return delGoods(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "businessManagement/goods/export",
        {
          ...this.queryParams
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>

